package org.iks.push.session;

import io.netty.channel.Channel;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.Attribute;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.iks.push.constant.ChannelConstant;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;

import java.util.Objects;

/**
 * @author kzou
 * @date 2024/1/3 13:57
 * @description:
 */
public class SessionManage {
    private static final DefaultChannelGroup defaultChannelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Nullable
    public static Channel findUserChannel(@NonNull String address) {
        for (Channel channel : defaultChannelGroup) {
            Attribute<String> account = channel.attr(ChannelConstant.getAccountAttrKey());
            if (Objects.equals(account.get(), address)) {
                return channel;
            }
            Attribute<String> userAddress = channel.attr(ChannelConstant.getPublicAddressAttrKey());
            if (Objects.equals(userAddress.get(), address)) {
                return channel;
            }
        }
        return null;
    }

    public static boolean addChannel(Channel channel) {
        Attribute<String> address = channel.attr(ChannelConstant.getPublicAddressAttrKey());
        if (address == null || address.get() == null) {
            return false;
        }
        defaultChannelGroup.add(channel);
        return true;
    }

}
